<script setup>
import {ref,onMounted} from 'vue'
import { Refresh, Search, Plus, Download, Delete } from "@element-plus/icons-vue";

import {getUserList, addUser, updateUser, deleteUser, deleteBatch,updateUserStatus,queryUsers} from "@/api/user.js";
import {ElMessage,ElMessageBox} from "element-plus";
// 响应式变量统一声明（按功能归类）
// 1. 表格核心数据
const tableData = ref([])
// 2. 分页配置
const pagination = ref({
  currentPage: 1,  // 当前页码
  pageSize: 10,    // 每页显示记录数
  total: 0         // 总记录数
})
// 3. 表单数据（新增/编辑）
const formData = ref({
  id: '',
  username: '',
  password: '',
  phone: '',
  photo: '',
  dept: '',
  createDate: '',
  status: ''
})
// 4. 搜索表单数据
const form = ref({
  username: '', // 用户名搜索条件
  status: null  // 状态搜索条件（null表示不筛选）
})
// 5. 其他功能变量
const formRef = ref(null)        // 表单实例
const title = ref('')            // 弹框标题
const multipleTable = ref(null)  // 表格实例
const selectedIds = ref([])      // 批量选中的ID数组
const dialogFormVisible = ref(false) // 新增/编辑弹框显示状态（补充缺失变量）


// 页面挂载：初始加载用getUserList（无搜索条件）
onMounted(() => {
  getData(false)
})


// 核心：数据获取方法（区分初始加载/搜索）
// isSearch: true=搜索（用queryUsers），false=初始加载（用getUserList）
const getData = (isSearch = false) => {
  // 1. 构建公共分页参数
  const baseParams = {
    currentPage: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  }
  // 2. 构建请求参数（搜索时附加筛选条件）
  const requestParams = isSearch
      ? { ...baseParams, username: form.value.username, status: form.value.status }
      : baseParams

  // 3. 区分接口调用
  const requestFn = isSearch ? queryUsers : getUserList

  // 4. 发起请求
  requestFn(requestParams)
      .then(res => {
        tableData.value = res.data.list
        pagination.value.total = res.data.total
      })
      .catch(error => {
        ElMessage.error(error.message || '数据获取失败')
      })
}


// 搜索功能：触发时调用queryUsers
const handleSearch = () => {
  pagination.value.currentPage = 1 // 搜索重置到第一页
  getData(true) // 传入true标识为搜索操作
}


// 分页操作：根据是否有搜索条件切换接口
// 每页条数改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  // 有搜索条件（用户名非空 或 状态已选择）则用queryUsers，否则用getUserList
  const hasSearchCondition = form.value.username || form.value.status !== null
  getData(hasSearchCondition)
}

// 页码改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  const hasSearchCondition = form.value.username || form.value.status !== null
  getData(hasSearchCondition)
}


// 新增用户：打开弹框
const handleAddMode1 = () => {
  dialogFormVisible.value = true
  title.value = "新增用户"
  reset() // 打开前重置表单
}


// 编辑用户：打开弹框并回显数据
const handleEdit = (row) => {
  dialogFormVisible.value = true
  title.value = "修改用户"
  // 深拷贝避免表单修改直接影响表格数据（修复引用类型问题）
  formData.value = JSON.parse(JSON.stringify(row))
}


// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度最短6位，最长15位', trigger: 'blur' }
  ],
  dept: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { trigger: 'blur', message: '请输入正确的手机号', pattern: /^1[3-9]\d{9}$/ }
  ]
}


// 提交表单：新增/编辑用户
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (!valid) return // 校验失败不执行后续操作

    // 区分新增/编辑接口
    const requestFn = formData.value.id ? updateUser : addUser

    requestFn(formData.value)
        .then(res => {
          if (res.code === 200) {
            ElMessage.success(res.message || (formData.value.id ? '修改成功' : '新增成功'))
            cancel() // 关闭弹框
            reset() // 重置表单
            // 提交后刷新数据：根据当前是否有搜索条件切换接口
            const hasSearchCondition = form.value.username || form.value.status !== null
            getData(hasSearchCondition)
          } else {
            ElMessage.error(res.message || '操作失败')
          }
        })
        .catch(error => {
          ElMessage.error(error.message || '接口请求失败')
        })
  })
}


// 取消操作：关闭弹框并重置表单
const cancel = () => {
  dialogFormVisible.value = false
  reset()
}


// 重置表单：清空新增/编辑表单数据
const reset = () => {
  formData.value = {
    id: '',
    username: '',
    password: '',
    phone: '',
    photo: '',
    dept: '',
    createDate: '',
    status: ''
  }
  // 重置表单校验状态（避免二次打开有残留校验提示）
  if (formRef.value) formRef.value.clearValidate()
}


// 文件上传成功：回显图片地址
const handleSuccess = (res) => {
  console.log('上传响应：', res)
  formData.value.photo = res.data || ''
}


// Excel导入成功：提示并刷新数据
const importExcelSuccess = (res) => {
  if (res.code === 200) {
    // 处理响应文本，按标点分割并过滤空值
    const parts = res.data.split(/[。;]/).filter(part => part.trim())
    const displayContent = parts.join('<br/>')

    ElMessageBox.alert(
        displayContent,
        '导入提示',
        { autofocus: false, dangerouslyUseHTMLString: true }
    ).then(() => {
      // 导入后刷新数据：适配当前是否有搜索条件
      const hasSearchCondition = form.value.username || form.value.status !== null
      getData(hasSearchCondition)
    })
  } else {
    ElMessage.error(res.message || 'Excel导入失败')
  }
}


// 单个删除：调用deleteUser接口
const handleDelete = (id) => {
  ElMessageBox.confirm(
      '数据删除将无法找回，确定删除？',
      '删除提示',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(() => {
    // 补充删除接口调用（原代码缺失）
    deleteUser(id)
        .then(res => {
          ElMessage.success(res.message || '删除成功')
          // 删除后刷新数据
          const hasSearchCondition = form.value.username || form.value.status !== null
          getData(hasSearchCondition)
        })
        .catch(error => {
          ElMessage.error(error.message || '删除失败')
        })
  }).catch(() => {
    ElMessage({ type: 'info', message: '已取消删除' })
  })
}


// 表格选中项变化：更新选中ID数组
const handleSelectionChange = (rows) => {
  selectedIds.value = rows.map(r => r.id)
}


// 批量删除：调用deleteBatch接口
const handleDeleteBatch = async (ids) => {
  try {
    await ElMessageBox.confirm(
        `共 ${ids.length} 条数据，删除后无法找回，是否继续？`,
        '批量删除提示',
        { type: 'warning' }
    )
    const res = await deleteBatch(ids)
    ElMessage.success(res.message || '批量删除成功')
    // 刷新数据并清空选中状态
    const hasSearchCondition = form.value.username || form.value.status !== null
    getData(hasSearchCondition)
    multipleTable.value.clearSelection()
  } catch (e) {
    console.error('批量删除错误：', e)
    if (e === 'cancel' || e === 'close') {
      ElMessage({ type: 'info', message: '已取消批量删除' })
    } else {
      ElMessage.error(e.message || '批量删除失败')
    }
  }
}


// 状态更新：调用updateUserStatus接口
async function handleStatusChange(row, val) {
  row._loading = true // 开启行加载动画
  try {
    await updateUserStatus(row.id, val)
    ElMessage.success('状态更新成功')
    // 刷新数据（保持当前筛选状态）
    const hasSearchCondition = form.value.username || form.value.status !== null
    getData(hasSearchCondition)
  } catch (e) {
    // 失败回滚开关状态
    row.status = val === '1' ? '0' : '1'
    ElMessage.error(e?.message || '状态更新失败')
  } finally {
    row._loading = false // 关闭加载动画
  }
}


// 文件导出：打开导出接口
const handleExport = () => {
  // 优化：附加当前搜索条件（若有），实现“按筛选结果导出”
  const exportUrl = new URL("http://localhost:8080/api/export")
  if (form.value.username) exportUrl.searchParams.append('username', form.value.username)
  if (form.value.status !== null) exportUrl.searchParams.append('status', form.value.status)
  window.open(exportUrl.toString())
}


// 搜索重置：清空条件并加载初始数据
function handleReset() {
  form.value.username = ''
  form.value.status = null
  pagination.value.currentPage = 1
  getData(false) // 重置后用初始加载接口（getUserList）
}
</script>

<template>
  <div class="user-box">
    <el-row>
      <el-col :span="24">
        <div class="grid-content ep-bg-purple-dark">
          <el-form :inline="true" :model="form">
            <el-form-item class="input-item">
              <el-input
                  v-model="form.username"
                  placeholder="请输入用户名称"
                  clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                  v-model="form.status"
                  class="m-2"
                  placeholder="请选择用户状态"
                  style="width: 240px"
                  clearable
              >
                <el-option label="启用" :value="'1'" />
                <el-option label="禁用" :value="'0'" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
              <el-button plain type="primary" :icon="Refresh" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="btn-group">
            <el-button type="primary" :icon="Plus" @click="handleAddMode1">添加</el-button>
           <el-upload :action="'http://localhost:8080/api/import'" :show-file-list="false" :on-success="importExcelSuccess"class="upload-excel">
             <el-button type="success" :icon="Download">导入</el-button>
           </el-upload>
            <el-button type="info" :icon="Download" @click="handleExport">导出</el-button>
            <el-button type="danger" :icon="Delete" @click="handleDeleteBatch(selectedIds)">批量删除</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-row>
      <div class="grid-content ep-bg-purple-dark" style="height: 150px">
        <el-table
            ref="multipleTable" :data="tableData" style="width: 100%"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55">

          </el-table-column>
          <el-table-column label="序号" width="120"type="index">
          </el-table-column>
          <el-table-column prop="username" label="用户名称">
          </el-table-column>
          <el-table-column prop="phone" label="电话号码">
          </el-table-column>
          <el-table-column prop="dept" label="所属部门">
          </el-table-column>
          <el-table-column prop="photo" label="照片">
            <template #default="scope">
              <el-image
                  style="width: 50px; height: 50px"
                  :src="'http://localhost:8080'+scope.row.photo"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="srcList"
                  show-progress
                  :initial-index="4"
                  fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
             <template #default="scope">
               <div class="demo-image__preview">
                 <el-switch v-model="scope.row.status" active-text="启用" inactive-text="禁用"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                            :active-value="'1'"  :inactive-value="'0'" inline-prompt
                            :loading="scope.row._loading"
                            @change="val => handleStatusChange(scope.row, val)"
                 ></el-switch>
               </div>
             </template>
          </el-table-column>
          <el-table-column prop="createDate" label="创建时间">
          </el-table-column>
          <el-table-column label="操作">
           <template #default="scope" >
             <div class="button-aa">
             <el-button  type="warning" @click="handleEdit(scope.row)">修改</el-button>
             <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
             </div>
           </template>

          </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            style="margin: 10px"
            :small="false"
            :disabled="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-sizes="[5, 10, 20, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
      </div>
    </el-row>
<!--    添加模态框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500">
      <el-form  ref="formRef"  :model="formData" :rules="rules">
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="username">
          <el-input autocomplete="off"  v-model="formData.username" size="large" placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLabelWidth" prop="phone">
          <el-input autocomplete="off" v-model="formData.phone" size="large" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="所属部门" :label-width="formLabelWidth" prop="dept">
          <el-input autocomplete="off"  v-model="formData.dept" size="large"  placeholder="请输入所属部门"/>
        </el-form-item>
        <el-form-item label="登录密码" :label-width="formLabelWidth" prop="password">
          <el-input autocomplete="off" v-model="formData.password"  size="large" show-password placeholder="请输入登录密码"/>
        </el-form-item>
        <el-form-item label="&nbsp;&nbsp;&nbsp状&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp态" :label-width="formLabelWidth" prop="status">
          <el-switch v-model="formData.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="&nbsp;&nbsp;&nbsp用户头像" :label-width="formLabelWidth" prop="photo">
          <el-upload class="el-upload-demo"
              v-model:file-list="fileList"
              action="http://localhost:8080/api/upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.grid-content{
  width: 99.5%;
  background-color: #ffffff;
 height: 110px;
  margin-top: 2px;
  margin-left: 1px;
}

.el-form {
  text-align: left;
}
.input-item {
  width: 200px;
  padding: 10px;
}


.el-select {
  margin-left: -30px;
}

.el-button:focus {
  outline: none;

}
.button-aa {
  display: flex;
  gap: 8px;
}

.btn-group {
  text-align: left;
  display: flex;
  margin-left: 20px;
  margin-top: -10px;
}
:deep(.el-dialog__header) {
  text-align: left;
}
.el-upload-demo{
  width: 100px;
  height: 100px;
}

.el-button:focus{
  outline: none;
}
.upload-excel{
  display: inline-block;
  margin-left: 10px;
  margin-right: 14px;
}
</style>